package com.demo.modules.system.controller;

import com.demo.common.core.domain.SysUserWxBo;
import com.demo.common.core.utils.ip.IpUtils;
import com.demo.common.redis.constants.CacheConstants;
import com.demo.common.redis.service.RedisService;
import com.demo.common.security.annotation.InnerAuth;
import com.demo.common.core.result.R;
import com.demo.common.core.utils.StringUtils;
import com.demo.common.core.utils.bean.BeanUtils;
import com.demo.common.datasource.web.controller.BaseController;
import com.demo.common.core.domain.LoginUser;
import com.demo.common.core.domain.SysUserBo;
import com.demo.common.security.utils.SecurityUtils;
import com.demo.modules.system.domain.sys.user.SysUserVo;
import com.demo.modules.system.service.ISysPermissionService;
import com.demo.modules.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MyPC
 */
@Api(tags = "A - 认证授权接口")
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseController {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private ISysPermissionService iSysPermissionService;

    @Autowired
    private RedisService redisService;

    @InnerAuth
    @GetMapping("/infoByUk/{uk}")
    public R<LoginUser> infoByUk(@PathVariable("uk") String uk) {
        SysUserBo sysUserBo = iSysUserService.findUserByUk(uk);
        if (StringUtils.isNull(sysUserBo)) {
            return R.fail("未查到账号信息！");
        }
        return R.ok(getLoginUser(sysUserBo));
    }

    @InnerAuth
    @GetMapping("/infoByMobile")
    @ApiOperation("根据手机号获取用户信息")
    public R<LoginUser> infoByMobile(@RequestParam("mobile") String mobile, @RequestParam("isCreate") Boolean isCreate) {
        SysUserBo sysUserBo = iSysUserService.findUserByMobile(mobile, isCreate);
        return R.ok(getLoginUser(sysUserBo));
    }

    @InnerAuth
    @GetMapping("/infoByMailbox")
    @ApiOperation("根据邮箱获取用户信息")
    public R<LoginUser> infoByMailbox(@RequestParam("mailbox") String mailbox, @RequestParam("isCreate") Boolean isCreate) {
        SysUserBo sysUserBo = iSysUserService.findUserByMailbox(mailbox, isCreate);
        return R.ok(getLoginUser(sysUserBo));
    }

    @InnerAuth
    @PostMapping("/infoByWx")
    @ApiOperation("根据微信获取用户信息")
    public R<LoginUser> infoByWx(@RequestBody SysUserWxBo sysUserWxBo) {
        SysUserBo sysUserBo = iSysUserService.findUserByWx(sysUserWxBo);
        return R.ok(getLoginUser(sysUserBo));
    }

    @InnerAuth
    @GetMapping("/register")
    public R<Boolean> registerUserInfo(@RequestParam("uk") String uk, @RequestParam("pk") String pk) {
        iSysUserService.registerUser(uk, pk);
        return R.ok(true);
    }

    @GetMapping("/getInfo")
    @ApiOperation("获取登录用户信息")
    public R<Map<String, Object>> getUserInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUserBo sysUserBo;
        if (StringUtils.isNotNull(loginUser)) {
            sysUserBo = loginUser.getSysUserBo();
        } else {
            sysUserBo = iSysUserService.selectByIdBo(SecurityUtils.getUserId());
        }
        SysUserVo sysUserVo = BeanUtils.copyDataProp(sysUserBo, new SysUserVo());
        sysUserVo.setUserId(String.valueOf(sysUserBo.getUserId()));
        // 角色集合
        Set<String> roles = iSysPermissionService.getRolePermission(sysUserBo);
        // 权限集合
        Set<String> permissions = iSysPermissionService.getMenuPermission(sysUserBo);
        Map<String, Object> map = new HashMap<>(3);
        map.put("user", sysUserVo);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return R.ok(map);
    }

    @GetMapping("/getLoginList")
    @ApiOperation("获取所有在线用户")
    public R<List<LoginUser>> getLoginList() {
        Set<String> keys = new HashSet<>(redisService.keys(CacheConstants.LOGIN_USER_KEY + "*"));
        List<LoginUser> loginUsers = new ArrayList<>();
        long currentTime = System.currentTimeMillis();
        for (String key : keys) {
            LoginUser loginUser = redisService.getCacheObject(key);
            if (currentTime > loginUser.getExpireTime()) {
                loginUsers.add(loginUser);
            }
        }
        return R.ok(loginUsers);
    }


    /**
     * 获取用户信息
     *
     * @param sysUserBo
     * @return
     */
    private LoginUser getLoginUser(SysUserBo sysUserBo) {
        // 角色集合
        Set<String> roles = iSysPermissionService.getRolePermission(sysUserBo);
        // 权限集合
        Set<String> permissions = iSysPermissionService.getMenuPermission(sysUserBo);
        LoginUser loginUser = new LoginUser();
        loginUser.setSysUserBo(sysUserBo);
        if (StringUtils.isNotEmpty(sysUserBo.getUk())) {
            loginUser.setAk(sysUserBo.getUk());
        } else {
            switch (sysUserBo.getRegisterType()) {
                case "2":
                    loginUser.setAk(sysUserBo.getMobile());
                    break;
                case "3":
                    loginUser.setAk(sysUserBo.getMailbox());
                    break;
                case "4":
                    loginUser.setAk(sysUserBo.getNickName());
                    break;
            }
        }
        loginUser.setUserId(sysUserBo.getUserId());
        loginUser.setRoles(roles);
        loginUser.setPermissions(permissions);
        return loginUser;
    }
}
